package com.sso.realm;




import com.common.entity.User;

import com.sso.openFeign.PermissionFeign;
import com.sso.token.UsernamePasswordToken;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;


/**
 * @create 2022-08-04
 */
public class MyRealm extends AuthorizingRealm {
    @Autowired
    private PermissionFeign permissionFeign;


    @Override
    //授权功能
    //当你进行权限校验就会走该方法
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }
    @Override
    public boolean supports(AuthenticationToken token) {

        System.out.println(token instanceof UsernamePasswordToken);

        return token instanceof UsernamePasswordToken;
    }
    @Override
    //认证功能
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        //1.获取登陆账号
        String username = authenticationToken.getPrincipal().toString();
        //2.根据账号查询用户信息
        User user = permissionFeign.findByUsername(username);
        //3.判断用户是否存在
        if (user!=null){
            //4.判断密码是否错误
            ByteSource salt= ByteSource.Util.bytes(user.getSalt());
            SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(user,user.getPassword(),salt,this.getName());
            return info;
        }
        return null;
    }

}
